//
//  InfiniteScrollView.m
//  test
//
//  Created by 汤丹峰 on 16/7/21.
//  Copyright © 2016年 汤丹峰. All rights reserved.
//

#import "InfiniteScrollView.h"
#import "InfiniteScrollCell.h"
#import "MYPageControl.h"

#define INFINITE_MAX_SECTIONS       100
#define INFINITE_CELL_IDENTIFIER    @"InfiniteScrollCell"

@interface InfiniteScrollView () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) MYPageControl *pageControl;
@end

@implementation InfiniteScrollView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // collectionview
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:flowLayout];
        self.collectionView = collectionView;
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerClass:[InfiniteScrollCell class] forCellWithReuseIdentifier:INFINITE_CELL_IDENTIFIER];
        collectionView.pagingEnabled = YES;
        collectionView.showsHorizontalScrollIndicator = NO;
        collectionView.scrollsToTop = NO;
        [self addSubview:collectionView];
        
        //pageControl
        MYPageControl *pageControl = [[MYPageControl alloc] initWithFrame:CGRectMake(0, frame.size.height - 10, [[UIScreen mainScreen] bounds].size.width - 20, 3)];
        self.pageControl = pageControl;
        pageControl.hidesForSinglePage = YES;
        [self addSubview:pageControl];
        
        //默认参数设值
        self.autoScrollTimeInterval = 3;
        self.autoScroll = YES;

    }
    return self;
}
- (void)setAutoScroll:(BOOL)autoScroll
{
    _autoScroll = autoScroll;
    
    [self removeTimer];
    if (autoScroll) {
        [self addTimer];
    }
}
- (void)setAutoScrollTimeInterval:(CGFloat)autoScrollTimeInterval
{
    _autoScrollTimeInterval = autoScrollTimeInterval;
    
    [self removeTimer];
    if (self.autoScroll) {
        [self addTimer];
    }
}
- (void)setImageURLStringsGroup:(NSArray *)imageURLStringsGroup
{
    _imageURLStringsGroup = imageURLStringsGroup;
    
    [self.collectionView reloadData];
    self.pageControl.numberOfPages = imageURLStringsGroup.count;
    
    [self removeTimer];
    if (self.autoScroll) {
        [self addTimer];
    }
}

- (void)removeTimer
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}
- (void)addTimer
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.autoScrollTimeInterval target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}

- (NSIndexPath *)resetIndexPath
{
    // 当前正在展示的位置
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    
    // 马上显示回最中间那组的数据
    NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:INFINITE_MAX_SECTIONS / 2];
    [self.collectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    return currentIndexPathReset;
}
- (void)nextPage
{
    // 马上显示回最中间那组的数据
    NSIndexPath *currentIndexPathReset = [self resetIndexPath];
    // 计算出下一个需要展示的位置
    NSInteger nextItem = currentIndexPathReset.item + 1;
    NSInteger nextSection = currentIndexPathReset.section;
    if (nextItem == self.imageURLStringsGroup.count) {
        nextItem = 0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    // 通过动画滚动到下一个位置
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageURLStringsGroup.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    InfiniteScrollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:INFINITE_CELL_IDENTIFIER forIndexPath:indexPath];
    [cell setImageView:self.imageURLStringsGroup[indexPath.item] placeholderImage:self.placeholderImage];
    return cell;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return INFINITE_MAX_SECTIONS;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(collectionView.frame.size.width, collectionView.frame.size.height);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.delegate) {
        [self.delegate infiniteScrollView:self didSelectItemAtIndex:indexPath.item];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.autoScroll) {
        [self addTimer];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSUInteger page = (NSUInteger)(scrollView.contentOffset.x / scrollView.bounds.size.width + 0.5) % self.imageURLStringsGroup.count;
    self.pageControl.currentPage = page;
}

@end
